#include "svgpreview.h"
#include "ui_svgpreview.h"

#include <QDebug>
#include <QPainter>
#include <QSvgRenderer>

#include <Qsci/qsciscintilla.h>

SvgPreview::SvgPreview(QWidget *parent, QsciScintilla *pEdit) :
    QWidget(parent),
    ui(new Ui::SvgPreview),
    m_pEdit(pEdit),
    s_defaultSize(QSize(1366,768))
{
    ui->setupUi(this);

    connect(m_pEdit, &QsciScintilla::textChanged,this,[=](){
        qDebug() << "textChanged";
        m_icon = iconFromSvgString(ui->label->size(), m_pEdit->text().toUtf8());

        ui->label->setPixmap(pixmapFromIcon(this->size(), m_icon));
    });
    m_icon = iconFromSvgString(s_defaultSize, m_pEdit->text().toUtf8());
    ui->label->setPixmap(pixmapFromIcon(this->size(), m_icon));

}

SvgPreview::~SvgPreview()
{
    delete ui;
}

QIcon SvgPreview::iconFromSvgString(QSize size, const QByteArray &svgs)
{
    QPixmap pixmap(size);
    QPainter painter(&pixmap);
    const QRect bounding_rect(QPoint(0, 0), size);

    if (!svgs.isEmpty()) {
        painter.setRenderHint(QPainter::Antialiasing, true);

        painter.setBrush(QBrush(Qt::white, Qt::SolidPattern));
        painter.setPen(Qt::NoPen);
        painter.drawRect(bounding_rect);

        QSvgRenderer svg(svgs);
        QSize target_size = svg.defaultSize();
        target_size.scale(size, Qt::KeepAspectRatio);
        QRect target_rect = QRect(QPoint(0, 0), target_size);
        target_rect.translate(bounding_rect.center() - target_rect.center());
        svg.render(&painter, target_rect);
    } else {
        painter.setBrush(QBrush(Qt::white, Qt::SolidPattern));
        painter.setPen(Qt::NoPen);
        painter.drawRect(bounding_rect);

        const int margin = 5;
        QRect target_rect = bounding_rect.adjusted(margin, margin, -margin, -margin);
        painter.setPen(Qt::SolidLine);
        painter.drawRect(target_rect);
        painter.drawLine(target_rect.topLeft(), target_rect.bottomRight() + QPoint(1, 1));
        painter.drawLine(target_rect.bottomLeft() + QPoint(0, 1), target_rect.topRight() + QPoint(1, 0));
    }

    QIcon icon;
    icon.addPixmap(pixmap);
    return icon;
}

QPixmap SvgPreview::pixmapFromIcon(QSize size, QIcon icon)
{
    return icon.pixmap(size);
}

void SvgPreview::resizeEvent(QResizeEvent *event)
{
    ui->label->setPixmap(pixmapFromIcon(ui->label->size(), m_icon));
}
